package com.game.common;

import com.game.message.task.QueueEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class QueueEventThread extends Thread {
	private static Logger logger = LoggerFactory.getLogger(QueueEventThread.class);
	@Resource
	private BlockingQueue<QueueEvent> blockingQueue;
	private static ExecutorService executor = Executors.newSingleThreadExecutor(new QueueEventThreadFactory("QueueEventThread"));

	@Override
	public void run() {
		while (true) {
			logger.info("QueueEventThread");
			try {
				final QueueEvent queueEvent = blockingQueue.take();
				Future<Boolean> future = executor.submit(() -> {
					long startTime = System.currentTimeMillis();
					boolean execute = queueEvent.execute();
					logger.info(queueEvent.getClass()+",用时：" + (System.currentTimeMillis() - startTime));
					return execute;
				});
				if (future.get(5000, TimeUnit.MILLISECONDS)) {
					logger.error("执行时间过长，任务名：" + queueEvent.getClass().getName());
				}
			} catch (Exception e) {
				logger.error("QueueEvent error", e);
			}
		}
	}

	public void addProcessorTask(final QueueEvent queueEvent) {
		try {
			this.blockingQueue.put(queueEvent);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

class QueueEventThreadFactory implements ThreadFactory {
	private final AtomicInteger poolNumber = new AtomicInteger(1);
	private final ThreadGroup group;
	private final AtomicInteger threadNumber = new AtomicInteger(1);
	private final String namePrefix;

	QueueEventThreadFactory(String prefix) {
		SecurityManager s = System.getSecurityManager();
		group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
		namePrefix = prefix + "-pool-" + poolNumber.getAndIncrement() + "-thread-";
	}

	public Thread newThread(Runnable r) {
		Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
		if (t.isDaemon())
			t.setDaemon(false);
		if (t.getPriority() != Thread.NORM_PRIORITY)
			t.setPriority(Thread.NORM_PRIORITY);
		return t;
	}
}
